package com.yunma.dialog;

import com.cmd.dos.hw.ShellScriInfo;
import com.cmd.dos.hw.ShellScriPanel;
import com.cmd.dos.hw.callback.CallbackWorker;
import com.cmd.dos.hw.util.ShellSwingWorker;
import com.common.util.SystemHWUtil;
import com.string.widget.util.ValueWidget;
import com.swing.dialog.DialogUtil;
import com.swing.dialog.GenericDialog;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckDnsDialog extends GenericDialog {

    /***
     * 集测的DNS
     */
    public static final String jiceDns = "172.18.24.45";
    private final ShellScriPanel shell1;
    private final ShellScriPanel shell2;
    private final ShellScriPanel shell3;
    private final ShellScriPanel shell4;
    private final ShellScriPanel shell5;
    private JButton checkButton;

    /**
     * Create the dialog.
     */
    public CheckDnsDialog(boolean modal) {
        setTitle("检查DNS");
        setLoc(getScreenWidth(), 500);
        setModal(modal);
        getContentPane().setLayout(new BorderLayout());
        JPanel contentPanel = new JPanel();
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(new GridLayout(1, 3, 0, 0));
        CallbackWorker callbackWorker1 = new CallbackWorker() {
            @Override
            public synchronized boolean callback(ShellSwingWorker shellSwingWorker, StringBuffer stringbuf, char temp) {
                return checkDNS(shellSwingWorker, stringbuf, temp, this);
            }

            @Override
            public void complete(String cmdResult) {
                checkButton.setEnabled(true);
            }
        };
        CallbackWorker callbackWorker2 = new CallbackWorker() {
            @Override
            public synchronized boolean callback(ShellSwingWorker shellSwingWorker, StringBuffer stringbuf, char temp) {
				/*String result=stringbuf.toString();
				if(result.contains("具有 32 字节的数据")){
					String envInfo=null;
					if(result.contains("[172.18.")){
						envInfo="集测环境";
					}else{
						envInfo="线上";
					}
					getShellScriPanel().updateDnsEnvInfo(envInfo);
				}*/
                return checkDNS(shellSwingWorker, stringbuf, temp, this);
            }

            @Override
            public void complete(String cmdResult) {
                checkButton.setEnabled(true);
            }
        };
        CallbackWorker callbackWorker3 = new CallbackWorker() {
            @Override
            public synchronized boolean callback(ShellSwingWorker shellSwingWorker, StringBuffer stringbuf, char temp) {
                return checkDNS(shellSwingWorker, stringbuf, temp, this);
            }

            @Override
            public void complete(String cmdResult) {
                checkButton.setEnabled(true);
            }
        };
        CallbackWorker callbackWorker4 = new CallbackWorker() {
            @Override
            public synchronized boolean callback(ShellSwingWorker shellSwingWorker, StringBuffer stringbuf, char temp) {
                return false;
            }

            @Override
            public void complete(String cmdResult) {
                System.out.println("cmdResult:\n" + cmdResult);

                //有时有缓存,所以不做判断
				/*
				 *   DNS 服务器  . . . . . . . . . . . : 192.168.8.57
   DNS 服务器  . . . . . . . . . . . : 172.18.24.45
   DNS 服务器  . . . . . . . . . . . : 172.18.24.45

				 * */
                String dnsInfo;
                if (cmdResult != null && isJice(cmdResult)) {
                    dnsInfo = "是集测DNS";
                    getShellScriPanel().updateDnsEnvInfo(dnsInfo, Color.red);
                } else {
                    dnsInfo = "不是集测DNS!!!";
                    getShellScriPanel().updateDnsEnvInfo(dnsInfo, Color.blue);
                }

//				checkButton.setEnabled(true);
            }
        };
        Color foregroundColor = Color.blue;
        shell1 = new ShellScriPanel(callbackWorker1, "官网后台", foregroundColor, new ShellScriInfo(null, false));
        shell2 = new ShellScriPanel(callbackWorker2, "官网前台", foregroundColor, new ShellScriInfo(null, false));
        shell3 = new ShellScriPanel(callbackWorker3, "应用商店", foregroundColor, new ShellScriInfo(null, false));
        shell4 = new ShellScriPanel(null, "www新官网", foregroundColor, new ShellScriInfo(null, false));
        shell5 = new ShellScriPanel(callbackWorker4, "当前DNS", foregroundColor, new ShellScriInfo(null, false));
        contentPanel.add(shell1);
        contentPanel.add(shell2);
        contentPanel.add(shell3);
        contentPanel.add(shell4);
        contentPanel.add(shell5);
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        checkButton = new JButton("重新检查环境");
        buttonPane.add(checkButton);
        checkButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                execute(null, null, null, null, true);
            }
        });
        getRootPane().setDefaultButton(checkButton);
        JButton cancelButton = new JButton("关闭");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CheckDnsDialog.this.setVisible(false);
            }
        });
        buttonPane.add(cancelButton);
        DialogUtil.escape2CloseDialog(this);
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            CheckDnsDialog dialog = new CheckDnsDialog(false);
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.execute("i.chanjet.com", "i.static.chanjet.com", "store.chanjet.com", "cloud.static.chanjet.com", true);
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 判断是否是集测DNS
     *
     * @param input
     * @return
     */
    public static boolean isJice(String input) {
        String regex = "[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}";//IP的正则表达式
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        List<String> list = new ArrayList<String>();
        while (matcher.find()) {
            String ip = matcher.group(0);
            System.out.println(ip);
            list.add(ip);
        }
        System.out.println(list.size());
        boolean isjice = true;
        for (int i = 0; i < list.size(); i++) {
            String array_element = list.get(i);
            if (!array_element.equals(jiceDns)) {
                isjice = false;
                break;
            }
        }
        System.out.println(isjice);
        return isjice;
    }

    private boolean checkDNS(ShellSwingWorker shellSwingWorker, StringBuffer stringbuf, char temp, CallbackWorker callbackWorker2) {
        String result = stringbuf.toString();
        if (result.contains("请求超时")/*&&temp=='。'*/) {
//			shellSwingWorker.cancel(true);
            return true;//中断
        }
        if (result.contains("具有 32 字节的数据") || result.contains("bytes from")) {
            String envInfo;
            if (result.contains("[172.18.22.170") || result.contains("(172.18.22.170")) {
                envInfo = "开发环境";
            } else if (result.contains("[172.18.20.28")
                    || result.contains("[172.18.20.68")
                    || result.contains("[172.18.2.212") || result.contains("(172.18.20.28")
                    || result.contains("(172.18.20.68")
                    || result.contains("(172.18.2.212")) {
//				ToastMessage toastMessage = new ToastMessage("集测环境",2000,Color.red);
//	            toastMessage.setVisible(true);
                envInfo = "集测环境";
            } else if (result.contains("[58.83.201.72")
                    || result.contains("[58.83.201.18")
                    || result.contains("[58.83.201.78") ||
                    result.contains("(58.83.201.72")
                    || result.contains("(58.83.201.18")
                    || result.contains("(58.83.201.78")) {
                envInfo = "线上";
            } else if (result.contains("[127.0.0.1") ||
                    result.contains("(127.0.0.1")) {
                envInfo = "本机";
            } else {
                envInfo = "仿真";
            }
            callbackWorker2.getShellScriPanel().updateDnsEnvInfo(envInfo);
        }
        return false;
    }

    public void execute(final String domain1, final String domain2, final String domain3, final String domain4, final boolean isExecute) {
//		EventQueue.invokeLater(new Runnable() {
//			@Override
//			public void run() {
        String pingCmd = "ping ";
        if (!SystemHWUtil.isWindows) {
            pingCmd = pingCmd + "-c 4 ";
        }
        shell1.cleanUpDnsEnvInfo();
        shell2.cleanUpDnsEnvInfo();
        shell3.cleanUpDnsEnvInfo();
        shell4.cleanUpDnsEnvInfo();

        if (!ValueWidget.isNullOrEmpty(domain1)) {
            shell1.setCmd(pingCmd + domain1);
        }
        if (isExecute)
            shell1.exeCommandAction();

        if (!ValueWidget.isNullOrEmpty(domain2)) {
            shell2.setCmd(pingCmd + domain2);
        }
        if (isExecute) {
            checkButton.setEnabled(false);
            shell2.exeCommandAction();
        }


        if (!ValueWidget.isNullOrEmpty(domain3)) {
            shell3.setCmd(pingCmd + domain3);
        }
        if (isExecute) {
            shell3.exeCommandAction();
        }
        if (!ValueWidget.isNullOrEmpty(domain4)) {
            shell4.setCmd(pingCmd + domain4);
        }
        if (isExecute) {
            shell4.exeCommandAction();
        }
        shell5.setCmd("ipconfig /all |findstr \"DNS\"|findstr [1-9][1-9]");
        if (isExecute) {
            shell5.exeCommandAction();
        }
//			}
//		});
    }
}
